package com.tanhua.admin.listener;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.templates.AliyunGreenTemplate;

import com.tanhua.dubbo.api.MovementsApi;
import com.tanhua.model.mongo.Movement;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class AuditListener {

    @DubboReference
    private MovementsApi movementApi;

    @Autowired
    private AliyunGreenTemplate template;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.audit.queue"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.audit.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "audit.movement"
            )
    )
    public void audit(String movementId) throws Exception {
        System.out.println("获取消息movementId=" + movementId);
        //1、根据id查询动态
        Movement movement = movementApi.findById(movementId);
        if (movement != null && movement.getState() == 0) {
            String content = movement.getTextContent(); //文本
            List<String> medias = movement.getMedias(); //图片
            // 2、调用工具类审核
            //这里应该做个判断，看下动态中有没有图片或者文字。如果没有，就不用审核
            //刚才的错误是，你发了一个动态，没有图片。所以空指针了 第51行
            if (!StringUtils.isEmpty(content) && !CollUtil.isEmpty(medias)) {
                Map<String, String> textMap = template.greenTextScan(content);
                Map<String, String> picMap = template.imageScan(medias);
                String textSugg = textMap.get("suggestion");
                String picSugg = picMap.get("suggestion");
                //3、更新数据库中的动态状态
                Integer state = 0; //还没审核
                if (textSugg.equals("pass") && picSugg.equals("pass")) {
                    state = 1;//通过
                } else if (textSugg.equals("block") || picSugg.equals("block")) {
                    state = 2; //不通过
                }
                movementApi.updateState(movementId, state);
            }
        }
    }
}

